package top.wilsonlv.jaguar.cloud.auth.api;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import top.wilsonlv.jaguar.cloud.upms.sdk.dto.DeviceBindDTO;
import top.wilsonlv.jaguar.cloud.upms.sdk.feign.RemoteDeviceService;
import top.wilsonlv.jaguar.commons.data.encryption.util.EncryptionUtil;
import top.wilsonlv.jaguar.commons.web.exception.impl.CheckedException;
import top.wilsonlv.jaguar.commons.web.response.JsonResult;
import top.wilsonlv.jaguar.commons.web.util.WebUtil;
import top.wilsonlv.jaguar.security.model.SecurityUser;
import top.wilsonlv.jaguar.security.util.SecurityUtil;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * @author lvws
 * @since 2021/12/17
 */
@RestController
@RequestMapping("/loginUser")
@RequiredArgsConstructor
@Api(tags = "登录用户Api")
public class LoginUserApi {

    private final RemoteDeviceService remoteDeviceService;

    @ApiOperation(value = "获取个人信息")
    @GetMapping("/info")
    public JsonResult<SecurityUser> info() {
        return JsonResult.success(SecurityUtil.getCurrentUser());
    }

    @ApiOperation(value = "绑定设备")
    @PostMapping("/bindDevice")
    public JsonResult<Void> bindDevice(@Valid @RequestBody DeviceBindDTO bindDTO,
                                       @RequestParam(required = false) String sign,
                                       @RequestParam(required = false) String nonce,
                                       @RequestParam(required = false) Long timestamp,
                                       HttpServletRequest request) {

        if (StringUtils.hasText(bindDTO.getDevicePublicKey())) {
            String error = EncryptionUtil.checkRequestBySign(timestamp, nonce, sign,
                    request.getParameterMap(), bindDTO.getDevicePublicKey());
            if (StringUtils.hasText(error)) {
                throw new CheckedException(error);
            }
        }

        remoteDeviceService.bindDevice(SecurityUtil.getCurrentUserId(), WebUtil.getHost(), bindDTO);
        return JsonResult.success();
    }

}
